package third.lib.zfb.common.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import third.lib.common.exception.ThirdException;
import third.lib.common.status.ThirdStatus;
import third.lib.utils.DateTimeUtils;
import third.lib.utils.StringRandUtils;

public class ZfbUtils {
    public static String getAuthInfo(String pid, String app_id, String priKey) throws ThirdException {
        Map<String, String> paramMap = buildAuthInfoMap(pid, app_id);
        String info = buildParam(paramMap);
        return info + "&" + getSign(paramMap, priKey);
    }

    public static String getOutTradeNo() {
        return DateTimeUtils.getCurTimeFormart("yyyyMMddHHmmss") + StringRandUtils.randNumberAndChar(6);
    }

    public static AlipayClient getRequest(String appId, String priKey, String pubCrtPath, String publAliPath, String rootCrtPath) throws ThirdException {
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
        certAlipayRequest.setAppId(appId);
        certAlipayRequest.setPrivateKey(priKey);
        certAlipayRequest.setFormat("json");
        certAlipayRequest.setCharset("utf-8");
        certAlipayRequest.setSignType("RSA2");
        certAlipayRequest.setCertPath(pubCrtPath);
        certAlipayRequest.setAlipayPublicCertPath(publAliPath);
        certAlipayRequest.setRootCertPath(rootCrtPath);

        try {
            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            return alipayClient;
        } catch (AlipayApiException var8) {
            var8.printStackTrace();
            throw new ThirdException(ThirdStatus.ZFB);
        }
    }

    public static Map<String, String> buildAuthInfoMap(String pid, String app_id) {
        Map<String, String> keyValues = new HashMap();
        keyValues.put("app_id", app_id);
        keyValues.put("pid", pid);
        keyValues.put("apiname", "com.alipay.account.auth");
        keyValues.put("methodname", "alipay.open.auth.sdk.code.get");
        keyValues.put("app_name", "mc");
        keyValues.put("biz_type", "openservice");
        keyValues.put("product_id", "APP_FAST_LOGIN");
        keyValues.put("scope", "kuaijie");
        keyValues.put("target_id", StringRandUtils.randNumberAndChar(18));
        keyValues.put("auth_type", "AUTHACCOUNT");
        keyValues.put("sign_type", "RSA2");
        return keyValues;
    }

    public static Map<String, String> getReturnParams(Map requestParams) {
        Map<String, String> params = new HashMap();
        Iterator iter = requestParams.keySet().iterator();

        while(iter.hasNext()) {
            String name = (String)iter.next();
            String[] values = (String[])((String[])requestParams.get(name));
            String valueStr = "";

            for(int i = 0; i < values.length; ++i) {
                valueStr = i == values.length - 1 ? valueStr + values[i] : valueStr + values[i] + ",";
            }

            params.put(name, valueStr);
        }

        return params;
    }

    public static String buildParam(Map<String, String> map) {
        List<String> keys = new ArrayList(map.keySet());
        Collections.sort(keys);
        StringBuilder sb = new StringBuilder();

        String tailValue;
        for(int i = 0; i < keys.size() - 1; ++i) {
            tailValue = (String)keys.get(i);
            String value = (String)map.get(tailValue);
            sb.append(buildKeyValue(tailValue, value, true));
            sb.append("&");
        }

        String tailKey = (String)keys.get(keys.size() - 1);
        tailValue = (String)map.get(tailKey);
        sb.append(buildKeyValue(tailKey, tailValue, true));
        return sb.toString();
    }

    public static String getTradeOut() {
        return DateTimeUtils.getMillis() + StringRandUtils.randNumberAndChar(19);
    }

    private static String buildKeyValue(String key, String value, boolean isEncode) {
        StringBuilder sb = new StringBuilder();
        sb.append(key);
        sb.append("=");
        if (isEncode) {
            try {
                sb.append(URLEncoder.encode(value, "UTF-8"));
            } catch (UnsupportedEncodingException var5) {
                sb.append(value);
            }
        } else {
            sb.append(value);
        }

        return sb.toString();
    }

    public static String getSign(Map<String, String> map, String priKey) throws ThirdException {
        List<String> keys = new ArrayList(map.keySet());
        Collections.sort(keys);
        StringBuilder authInfo = new StringBuilder();

        String tailValue;
        String oriSign;
        for(int i = 0; i < keys.size() - 1; ++i) {
            tailValue = (String)keys.get(i);
            oriSign = (String)map.get(tailValue);
            authInfo.append(buildKeyValue(tailValue, oriSign, false));
            authInfo.append("&");
        }

        String tailKey = (String)keys.get(keys.size() - 1);
        tailValue = (String)map.get(tailKey);
        authInfo.append(buildKeyValue(tailKey, tailValue, false));
        oriSign = sign(authInfo.toString(), priKey);
        String encodedSign = "";

        try {
            encodedSign = URLEncoder.encode(oriSign, "UTF-8");
            System.out.println(encodedSign);
        } catch (UnsupportedEncodingException var9) {
            var9.printStackTrace();
            throw new ThirdException(ThirdStatus.ZFB);
        }

        return "sign=" + encodedSign;
    }

    public static String sign(String content, String privateKey) throws ThirdException {
        String sign = "";

        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
            KeyFactory keyf = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
            Signature signature = Signature.getInstance("SHA256WithRSA");
            signature.initSign(priKey);
            signature.update(content.getBytes("UTF-8"));
            byte[] signed = signature.sign();
            sign = Base64.encodeBase64String(signed);
            return sign;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new ThirdException(ThirdStatus.ZFB);
        }
    }
}
